package cn.kent.simple;


/**
 * 485. 最大连续 1 的个数
 *
 * 空间复杂度： O(1)
 * 时间复杂度： O(n) n为数组长度，一次遍历所以为n
 */
public class FindMaxConsecutiveOnes {
    public static void main(String[] args) {
        int[] nums = {1, 1, 0, 1, 1, 1};
        int maxConsecutiveOnes = findMaxConsecutiveOnes2(nums);
        System.out.println(maxConsecutiveOnes);
    }

    /**
     * 将num==1的求max放到了最后
     * 压缩时间到1ms
     */
    public static int findMaxConsecutiveOnes2(int[] nums) {
        int sum = 0;
        int res = 0;
        for (int num : nums) {
            if (num == 1)
                sum++;
            else {
                res = Math.max(res, sum);
                sum = 0;
            }
        }
        res = Math.max(res, sum);
        return res;
    }

    /**
     * 2ms
     */
    public static int findMaxConsecutiveOnes(int[] nums) {
        int sum = 0;
        int res = 0;
        for (int num : nums) {
            if (num == 1)
                sum++;
            else
                sum = 0;
            res = sum != 0 && sum > res ? sum : res;
        }
        return res;
    }
}
